package com.platform.common.web.intercepors;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.common.config.CaptchaConfig;
import com.platform.common.config.PlatformConfig;
import com.platform.common.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码拦截器
 */
@Component
public class CaptchaInterceptor implements HandlerInterceptor {

    private ObjectMapper mapper = new ObjectMapper();

    @Resource
    private CaptchaConfig captchaConfig;
    @Autowired
    private PlatformConfig platformConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (PlatformConfig.YES.equals(platformConfig.getAuthCode())) {
            // 获得页面来的验证码
            String captchaCode = request.getParameter("captchaCode");
            if (!captchaConfig.verify(captchaCode)) {
                mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
                String json = mapper.writeValueAsString(AjaxResult.fail("验证码不正确"));
                response.getWriter().print(json);
                return false;
            }
        }
        return true;
    }
}
